<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :span="16">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <span style="font-size: 18px">订餐规则</span>
                    </div>
                    <el-form :model="schoolRuleForm" :rules="rules2" v-loading="loading" ref="schoolRuleForm" label-width="140px" class="demo-schoolRuleForm">
                        <el-row :gutter="20">
                            <el-col :span="8">
                                <el-form-item label="次日早餐截止时间" prop="morning_deadline">
                                    <el-tooltip class="item" effect="dark" content="在当天预定次日早餐的截止时间" placement="right">
                                        <el-time-picker
                                                :readonly="!canModifyRule"
                                                style="width: 250px;margin-bottom: 0"
                                                v-model="schoolRuleForm.morning_deadline"
                                                value-format="HH:mm"
                                                format="HH:mm"
                                                placeholder="次日早餐截止时间">
                                        </el-time-picker>
                                    </el-tooltip>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="次日午餐截止时间" prop="lunch_deadline">
                                    <el-tooltip class="item" effect="dark" content="在当天预定次日午餐的截止时间" placement="right">
                                        <el-time-picker
                                                :readonly="!canModifyRule"
                                                style="width: 250px;margin-bottom: 0"
                                                v-model="schoolRuleForm.lunch_deadline"
                                                value-format="HH:mm"
                                                format="HH:mm"
                                                placeholder="次日午餐截止时间">
                                        </el-time-picker>
                                    </el-tooltip>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="次日晚餐截止时间" prop="dinner_deadline">
                                    <el-tooltip class="item" effect="dark" content="在当天预定次日晚餐的截止时间" placement="right">
                                        <el-time-picker
                                                :readonly="!canModifyRule"
                                                style="width: 250px;margin-bottom: 0"
                                                v-model="schoolRuleForm.dinner_deadline"
                                                value-format="HH:mm"
                                                format="HH:mm"
                                                placeholder="次日晚餐截止时间">
                                        </el-time-picker>
                                    </el-tooltip>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="8">
                                <el-form-item label="早餐时间" prop="morning_date">
                                    <el-time-picker
                                            :readonly="!canModifyRule"
                                            style="width: 250px"
                                            is-range
                                            v-model="schoolRuleForm.morning_date"
                                            range-separator="~"
                                            value-format="HH:mm:ss"
                                            start-placeholder="早餐开始时间"
                                            end-placeholder="早餐结束时间"
                                            placeholder="选择早餐时间范围">
                                    </el-time-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="午餐时间" prop="lunch_date" required>
                                    <el-time-picker
                                            :readonly="!canModifyRule"
                                            style="width: 250px"
                                            is-range
                                            v-model="schoolRuleForm.lunch_date"
                                            range-separator="~"
                                            value-format="HH:mm:ss"
                                            start-placeholder="午餐开始时间"
                                            end-placeholder="午餐结束时间"
                                            placeholder="选择午餐时间范围">
                                    </el-time-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="晚餐时间" prop="dinner_date" required>
                                    <el-time-picker
                                            :readonly="!canModifyRule"
                                            style="width: 250px"
                                            is-range
                                            v-model="schoolRuleForm.dinner_date"
                                            range-separator="~"
                                            value-format="HH:mm:ss"
                                            start-placeholder="晚餐开始时间"
                                            end-placeholder="晚餐结束时间"
                                            placeholder="选择晚餐时间范围">
                                    </el-time-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="8">
                                <el-form-item label="默认早餐规则" prop="morning_rule">
                                    <el-select :disabled="!canModifyRule" style="width: 250px" v-model="schoolRuleForm.morning_rule" placeholder="请选择早餐规则">
                                        <el-option label="手动" value="0"></el-option>
                                        <el-option label="自动" value="1"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="默认午餐规则" prop="lunch_rule">
                                    <el-select :disabled="!canModifyRule" style="width: 250px" v-model="schoolRuleForm.lunch_rule" placeholder="请选择午餐规则">
                                        <el-option label="手动" value="0"></el-option>
                                        <el-option label="自动" value="1"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="默认晚餐规则" prop="dinner_rule">
                                    <el-select :disabled="!canModifyRule" style="width: 250px" v-model="schoolRuleForm.dinner_rule" placeholder="请选择晚餐规则">
                                        <el-option label="手动" value="0"></el-option>
                                        <el-option label="自动" value="1"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item label="加餐日期限制" prop="is_limit">
                                    <el-switch
                                            v-model="schoolRuleForm.is_limit"
                                            :active-value="1"
                                            :inactive-value="0"
                                            active-color="#13ce66"
                                            inactive-color="#ff4949">
                                    </el-switch>
                                    <el-tooltip class="item" effect="dark" placement="right">
                                        <i class="el-icon-info" style="margin-left: 30px"></i>
                                        <div slot="content">
                                            若限制则只能从明天开始选择，且在加餐截止时间之前；<br/>
                                            若不限制则从今天开始选择，且不考虑加餐截止时间
                                        </div>
                                    </el-tooltip>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div style="text-align: right">
                        <el-button v-permission="'school-rules.update'" @click="resetForm('schoolRuleForm')">取消</el-button>
                        <el-button type="primary" :loading="btnLoading" v-permission="'school-rules.update'" @click="submitSchoolRuleForm">保存</el-button>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <span style="font-size: 18px">基本信息</span>
                    </div>

                    <el-form :model="schoolForm" :rules="rules" v-loading="loading2" ref="schoolForm" label-width="140px" class="demo-schoolForm">
                        <el-form-item label="学校名称">{{ schoolForm.name }}</el-form-item>
                        <el-form-item label="联系人" prop="contact_name">
                            <el-input :disabled="!canModifySchool" style="width: 250px" v-model="schoolForm.contact_name"></el-input>
                        </el-form-item>
                        <el-form-item label="联系电话" prop="contact_phone">
                            <el-input :disabled="!canModifySchool" style="width: 250px" v-model="schoolForm.contact_phone"></el-input>
                        </el-form-item>
                        <el-form-item label="地址" prop="areaId" required>
                            <jw-area :disabled="!canModifySchool" style="width: 250px" v-model="schoolForm.areaId" :init="initArea"></jw-area>
                        </el-form-item>
                        <el-form-item label="详细地址" prop="detail_address">
                            <el-input :disabled="!canModifySchool" style="width: 400px" v-model="schoolForm.detail_address"></el-input>
                        </el-form-item>
                    </el-form>
                    <div style="text-align: right">
                        <el-button v-permission="'schools.update'" @click="cancelSchoolForm('schoolForm')">取消</el-button>
                        <el-button type="primary" v-permission="'schools.update'" @click="submitSchoolForm" :loading="btnLoading2">保存</el-button>
                    </div>

                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    import { showSchoolRule, editSchoolRule, showSchool, editSchool } from '@/api/school'
    import { isPhoneAvailable } from '@/utils/validate'
    import JwArea from '@/components/Area'
    export default {
      name: 'schoolRule',
      computed: {
        canModifyRule() {
          for (let i = 0; i < this.$store.getters.permissions.length; i++) {
            if (this.$store.getters.permissions[i] === 'school-rules.update') {
              return true
            }
          }
          return false
        },
        canModifySchool() {
          for (let i = 0; i < this.$store.getters.permissions.length; i++) {
            if (this.$store.getters.permissions[i] === 'schools.update') {
              return true
            }
          }
          return false
        }
      },
      data() {
        const validateLunch = (rule, value, callback) => {
          if (!this.schoolRuleForm.lunch_date) {
            callback(new Error('请选择午餐时间'))
          } else {
            if (this.schoolRuleForm.morning_date) {
              if (!(this.schoolRuleForm.morning_date[1] <= this.schoolRuleForm.lunch_date[0])) {
                callback(new Error('中餐和午餐时间不能有重叠'))
              }
            }
            callback()
          }
        }
        const validateDinner = (rule, value, callback) => {
          if (!this.schoolRuleForm.dinner_date) {
            callback(new Error('请选择晚餐时间'))
          } else {
            if (this.schoolRuleForm.morning_date) {
              if (!(this.schoolRuleForm.morning_date[1] <= this.schoolRuleForm.dinner_date[0])) {
                callback(new Error('中餐和晚餐时间不能有重叠'))
              }
            }
            if (this.schoolRuleForm.lunch_date) {
              if (!(this.schoolRuleForm.lunch_date[1] <= this.schoolRuleForm.dinner_date[0])) {
                callback(new Error('午餐和晚餐时间不能有重叠'))
              }
            }
            callback()
          }
        }
        const validatePhone = (rule, value, callback) => {
          if (!isPhoneAvailable(value)) {
            callback(new Error('手机号码格式错误'))
          }
          callback()
        }
        return {
          initArea: [],
          rules: {
            areaId: [
              { required: true, message: '请选择所属省市区', trigger: 'blur' }
            ],
            detail_address: [
              { required: true, message: '请输入详细地址', trigger: 'blur' }
            ],
            contact_name: [
              { required: true, message: '请输入联系人名称', trigger: 'blur' },
              { min: 2, max: 20, message: '输入的联系人名称长度在2 ~ 20个字符之间' }
            ],
            contact_phone: [
              { required: true, message: '请输入联系电话', trigger: 'blur' },
              { validator: validatePhone, trigger: 'blur' }
            ]
          },
          btnLoading: false,
          btnLoading2: false,
          loading: true,
          loading2: true,
          schoolRuleForm: {
            id: '',
            morning_rule: 0,
            morning_date: [],
            lunch_rule: 0,
            lunch_date: [],
            dinner_rule: 0,
            dinner_date: [],
            morning_deadline: '',
            lunch_deadline: '',
            dinner_deadline: '',
            is_limit: 0
          },
          schoolForm: {
            id: '',
            name: '',
            contact_name: '',
            contact_phone: '',
            address: '',
            detail_address: ''
          },
          rules2: {
            morning_rule: [
              { required: true, message: '请选择早餐规则', trigger: 'blur' }
            ],
            morning_date: [
              { required: true, message: '请选择早餐时间', trigger: 'blur' }
            ],
            lunch_rule: [
              { required: true, message: '请选择午餐规则', trigger: 'blur' }
            ],
            lunch_date: [
              { validator: validateLunch, trigger: 'blur' }
            ],
            dinner_rule: [
              { required: true, message: '请选择晚餐规则', trigger: 'blur' }
            ],
            dinner_date: [
              { validator: validateDinner, trigger: 'blur' }
            ],
            morning_deadline: [
              { required: true, message: '请选择截止时间', trigger: 'blur' }
            ],
            lunch_deadline: [
              { required: true, message: '请选择截止时间', trigger: 'blur' }
            ],
            dinner_deadline: [
              { required: true, message: '请选择截止时间', trigger: 'blur' }
            ]
          }
        }
      },
      components: {
        JwArea: JwArea
      },
      methods: {
        cancelSchoolForm(formName) {
          this.$refs[formName].clearValidate()
          this.editSchool()
        },
        resetForm(formName) {
          this.$refs[formName].clearValidate()
          this.editSchoolRule()
        },
        getUserInfo() {
          this.editSchoolRule()
          this.editSchool()
        },
        submitSchoolRuleForm() {
          this.$refs['schoolRuleForm'].validate((valid) => {
            if (valid) {
              // 通过校验
              this.loading = true
              this.btnLoading = true
              editSchoolRule(this.schoolRuleForm, this.schoolRuleForm.id).then(res => {
                if (res.result === 'failed') {
                  this.$message.error(res.msg)
                } else {
                  this.$message.success('保存成功')
                  this.editSchoolRule()
                }
                this.loading = false
                this.btnLoading = false
              }).catch(err => {
                this.$handleNotFound(err, '学校规则不存在')
                this.loading = false
                this.btnLoading = false
              })
            }
          })
        },
        editSchool() {
          showSchool().then(res => {
            Object.assign(this.schoolForm, res)
            this.initArea = [
              parseInt(res.province),
              parseInt(res.city),
              parseInt(res.country)
            ]
            this.schoolForm.areaId = this.initArea
            this.loading = false
            this.loading2 = false
          })
        },
        editSchoolRule() {
          showSchoolRule().then(res => {
            if (res) {
              this.schoolRuleForm.id = res.id
              this.schoolRuleForm.morning_deadline = res.morning_deadline
              this.schoolRuleForm.lunch_deadline = res.lunch_deadline
              this.schoolRuleForm.dinner_deadline = res.dinner_deadline
              this.schoolRuleForm.morning_rule = res.morning_rule.toString()
              this.schoolRuleForm.lunch_rule = res.lunch_rule.toString()
              this.schoolRuleForm.dinner_rule = res.dinner_rule.toString()
              this.schoolRuleForm.morning_date = [res.morning_start, res.morning_end]
              this.schoolRuleForm.lunch_date = [res.lunch_start, res.lunch_end]
              this.schoolRuleForm.dinner_date = [res.dinner_start, res.dinner_end]
              this.schoolRuleForm.is_limit = res.is_limit
            }
          })
        },
        // 提交学校表单
        submitSchoolForm() {
          this.btnLoading2 = true
          this.$refs['schoolForm'].validate((valid) => {
            if (valid) {
              // 通过校验
              this.loading2 = true
              editSchool(this.schoolForm, this.schoolForm.id).then(res => {
                this.$message.success('编辑成功')
                this.editSchool()
                this.btnLoading2 = false
                this.loading2 = false
              }).catch(err => {
                this.$handleNotFound(err, '学校不存在')
                this.btnLoading2 = false
                this.loading2 = false
              })
            } else {
              this.btnLoading2 = false
            }
          })
        }
      },
      created() {
        this.getUserInfo()
      }
    }
</script>

<style scoped>
    .el-row {
        margin-bottom: 10px;
    }
    .el-col {
        border-radius: 4px;
    }
    .text {
        font-size: 14px;
    }

    .item {
        margin-bottom: 18px;
    }
    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }
    .school-form {
        margin: 12px 0;
        display: block;
        float: left;
        width: 100%;
    }
    .school-form-title {
        display: block;
        float: left;
    }
    .school-form-content {
        display: block;
        float: right;
    }
</style>
